import {Button, Divider, Select,} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import { PageContainer, } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import Moment from 'moment';
import {queryDay,queryRecords,exportRecord} from './service';
import {getPayOrder} from "@/pages/VipManagement/IntegralDay/service";
import OrderCommon from "@/pages/OrderCommon";
import styles from "@/global.less";

import {saveFileAs} from "@/utils/utils";
import Access from '@/components/Access/Access';

const TableList = (props) => {
  const [payOrderValues, setPayOrderValues] = useState({});
  const [order, setOrder] = useState(false);
  const [createModalVisible, handleModalVisible] = useState(false);
  const [count, setCount] = useState(0);
  const [detailCount, setDetailCount] = useState(0);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef();
  const [memberNumber, setMemberNum] = useState('');
  const [integralRecords, setIntegralRecords] = useState(false);
  const [outModal, handleOutModal] = useState(false);

  const handlePay = (params) => {
    getPayOrder(params).then((res) => {
      const {code, data} = res;
      code === 0 ? (setPayOrderValues(data), setOrder(true)) : null;
    });
  };
  useEffect(() => {
    const { query } = props.history.location;
    if (query?.memberNumber){
      setMemberNum(query?.memberNumber);
      actionRef.current.reload();
    }

  }, [props.history.location.query?.memberNumber]);

  const columnsDay = [
    {
      title: '会员名',
      dataIndex: 'memberName',
      render: (dom) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '会员手机号',
      dataIndex: 'memberMobile',
    },
    {
      title: '会员卡号',
      dataIndex: 'memberNumber',
    },
    {
      title: '所获积分',
      dataIndex: 'integral',
    },
    {
      title: '赠送日期',
      dataIndex: 'currentDate',
      hideInSearch: true,
      render: (dom) => {
        return <span>{ Moment(dom).format('yyyy-MM')}</span>;;
      },
    },
    {
      title: '是否到账',
      dataIndex: 'returnType',
      hideInSearch: true,
      render: (dom) => {
        return <span>{ dom?'已到账':'未到账'}</span>;;
      },
    },
    {
      title: '积分来源',
      dataIndex: 'type',
      // valueEnum: {
      //   1: {
      //     text: '充值',
      //     status: 'Processing',
      //   },
      //   2: {
      //     text: '消费',
      //     status: 'Success',
      //   },
      // },
      render: (dom) => {

        return <span>{(dom === 1? '消费':(dom === 2?'余额':'补偿')) }</span>;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return <a
          onClick={() => {
            if (record.type === 1){
              handlePay(record.billId);
              setOrder(true);
            }
          }}
        >
          {record.type === 1 ? "查看订单详情" : ""}
        </a>;

      }
    },
  ];
  const columns = [
    {
      title: '会员卡号',
      dataIndex: 'memberNumber',
    },
    {
      title: '会员名',
      dataIndex: 'memberName',
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '会员手机号',
      dataIndex: 'memberMobile',
    },
    {
      title: '到账前积分余额',
      dataIndex: 'oldIntegral',
      hideInSearch: true,
    },
    {
      title: '所获积分',
      dataIndex: 'integral',
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueEnum: {
        1: {
          text: '消费',
          status: 'Processing',
        },
        2: {
          text: '余额',
          status: 'Success',
        },
        3: {
          text: '混合',
          status: 'Error',
        },
        4: {
          text: '活动赠送',
          status: 'Error',
        },
      },
    },
    {
      title: '日期',
      dataIndex: 'createTime',
      hideInSearch: true,
      render:(dom)=>{return <div>{new Date(dom).toLocaleString()}</div>}
    },
    {
      title: '日期',
      dataIndex: 'created_at',
      hideInTable: true,
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startCreateTime: value[0],
            endCreateTime: value[1],
          };
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Access accessKey={"@detailIntegral"}>
          <a
            onClick={() => {
              handleModalVisible(true);
              setStepFormValues(record);

            }}
          >
            查看详情
          </a>
          <Divider type="vertical" />
        </Access>
        ,
      ],
    },
  ];
  const outColumns = [
    {
      title: '到账日期',
      dataIndex: 'created_at',
      hideInTable: true,
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="到账记录表格"
        actionRef={actionRef}
        rowKey="PointsManagement"
        scroll={{x:1200}}
        bordered
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Access accessKey={"@downloadIntegral"}>
            <Button loading={integralRecords} type="primary" onClick={() => {
              handleOutModal(true);
              setIntegralRecords(true);
            }}>
              导出到账记录
            </Button>
          </Access>

        ]}
        request={(params, sorter, filter) => {
          if (memberNumber){
            return queryRecords({ ...params, sorter, filter ,memberNumber:memberNumber});
          }else {
            return queryRecords({ ...params, sorter, filter});
          }
        }}
        postData={(params) => {
          setMemberNum();
          const { list, total } = params;
          setCount(total);
          return list;
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        onReset={(params) => {
          setMemberNum();
          actionRef.current.reload();
        }}
        columns={columns}
      />
      <CreateForm
        width={1000}
        title={'到账记录详情'}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >

        <ProTable
          scroll={{x:800}}
          bordered
          footer={null}
          toolBarRender={false}
          search={false}
          request={(params, sorter, filter) => {
            params.id = stepFormValues.id;
            return queryDay(params);
          }}
          postData={(params) => {
            const { list, total } = params;
            setDetailCount(total);
            return list;
          }}
          pagination={{
            defaultPageSize: 30,
            showSizeChanger: true,
            showTitle: false,
            total: detailCount,
            showTotal: (total) => `共${total}条`,
          }}

          columns={columnsDay}
        />


      </CreateForm>
      <CreateForm
        title={'订单详情'}
        width={1300}
        onCancel={() => setOrder(false)}
        modalVisible={order}
      >
        <OrderCommon
          payOrderValues={payOrderValues}
          refund={false}
        />
      </CreateForm>
      <CreateForm
        title={'导出信息'}
        width={800}
        footer={null}
        onCancel={() => {
          handleOutModal(false);
          setIntegralRecords(false);
        }}
        modalVisible={outModal}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            handleOutModal(false);
            exportRecord(value).then(res=>{
              if (res){
                saveFileAs(res, '积分到账记录');
              }
              setIntegralRecords(false);
            })
          }}
          rowKey={r=>r.id}
          bordered
          type="form"
          columns={outColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
